package org.aplikator.client.command;

import org.aplikator.client.Aplikator;
import org.aplikator.client.data.Record;
import org.aplikator.client.descriptor.FunctionDTO;
import org.aplikator.client.rpc.Callback;
import org.aplikator.client.rpc.impl.GetFunction;
import org.aplikator.client.rpc.impl.GetFunctionResponse;
import org.aplikator.client.rpc.impl.RunFunction;
import org.aplikator.client.rpc.impl.RunFunctionResponse;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Label;

@SuppressWarnings("serial")
public class ExecuteFunction extends BindableCommand {

    @SuppressWarnings("unused")
    private ExecuteFunction() {
    }

    public ExecuteFunction(String functionId) {
        super();
        this.functionId = functionId;
    }

    private FunctionDTO function;

    private String functionId;

    @Override
    public void execute() {
        if (function == null) {
            Aplikator.aplikatorService.execute(new GetFunction(functionId), new Callback<GetFunctionResponse>() {
                public void process(GetFunctionResponse response) {
                    ExecuteFunction.this.function = response.getFunction();
                    drawPanel();
                }
            });
        } else {
            drawPanel();
        }

    }

    private void drawPanel() {
        mainPanel.setContents(new Label("Started function " + function.getLocalizedName()));
        Record functionParameters = null;// TODO functionParameters from
                                         // function descriptor and wizard

        Aplikator.aplikatorService.execute(new RunFunction(function, Aplikator.clientContext.clone(), functionParameters), new Callback<RunFunctionResponse>() {
            public void process(RunFunctionResponse response) {
                Window.alert(response.getResponse()); // TODO better response
            }
        });

    }

}
